package com.simdo.g768.Mqtt;

import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.MqttCallback;

import info.mqtt.android.service.MqttAndroidClient;

public class MqttManage {

    private MqttAndroidClient mClient;
    private static MqttManage instance;

    public MqttManage() {}

    public static MqttManage build() {
        synchronized (MqttManage.class) {
            if (instance == null) instance = new MqttManage();
        }
        return instance;
    }

    public void connect(MqttConnection connection, IMqttActionListener listener, MqttCallback callback) {
        mClient = connection.getMqttAndroidClient();
        mClient.connect(connection.getMqttConnectOptions(), null, listener);
        mClient.setCallback(callback);
    }

    public void disconnect() {
        if (notConnected()) return;
        mClient.disconnect();
    }

    public void subscribe(Subscription subscription, IMqttActionListener listener) {
        if (notConnected()) return;
        mClient.subscribe(subscription.getTopic(), subscription.getQos(), null, listener);
    }

    public void unsubscribe(String topic) {
        if (notConnected()) return;
        mClient.unsubscribe(topic);
    }

    public void publish(Publish publish, IMqttActionListener callback) {
        if (notConnected()) return;
        mClient.publish(publish.getTopic(), publish.getPayload().getBytes(), publish.getQos(), publish.isRetained(), null, callback);
    }

    public boolean notConnected() {
        return mClient == null || !mClient.isConnected();
    }
}
